package com.cloud.xtools.common.filter;

import com.cloud.xtools.common.redis.RedisService;
import com.cloud.xtools.common.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author Daixinguo
 */
@Component
@RequiredArgsConstructor
public class SecurityAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;

    private final RedisService redisService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // if (request.getHeader("Authorization") != null && !request.getHeader("Authorization").isEmpty()) {
        //     String token = request.getHeader("Authorization");
        //
        //     // 解析 token 如果不存在 token 则交由后续的拦截器处理，在控制器中将通过 @DisAuth 注解跳过权限检查
        //     if (!jwtUtil.isTokenExpired(token)) {
        //         // 获取 jwt id
        //         String jwtId = jwtUtil.extractId(token);
        //         // System.out.println(jwtId);
        //         if (redisService.getString(jwtId) != null){
        //
        //             request.setAttribute("username", jwtUtil.extractUsername(token));
        //             request.setAttribute("user_id", jwtUtil.getUserId(token));
        //         }
        //     }
        // }

        // System.out.println("SecurityAuthenticationFilter");
        // System.out.println(request.getHeader("user-id"));
        // System.out.println(request.getHeader("permissions"));

        request.setAttribute("username", request.getHeader("username"));
        request.setAttribute("user_id", request.getHeader("user-id"));
        request.setAttribute("permissions", request.getHeader("permissions"));

        filterChain.doFilter(request, response);
    }
}
